package com.huluobo.document.view

import android.os.Environment
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.document.DocumentIntent
import com.huluobo.document.DocumentViewModel
import com.huluobo.document.R
import com.huluobo.lib_base.BaseApp
import com.huluobo.lib_base.HttpType
import com.huluobo.lib_base.LocalEntity
import com.huluobo.lib_base.UIState
import kotlinx.coroutines.launch

/**
 *  Created by LC on 2025/3/14.
 */

@Composable
fun LocalPage(navHostController: NavHostController, vm: DocumentViewModel = hiltViewModel()) {
    val file = BaseApp.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
    val list = remember {
        SnapshotStateList<LocalEntity>()
    }

    var checkName by remember {
        mutableStateOf("")
    }
    var checkPath by remember {
        mutableStateOf("")
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        Log.e("TagA", "读取本地文件失败:${it.msg}")
                    }

                    UIState.OnLoading -> {}
                    is UIState.OnSuccess<*> -> {
                        if (it.type == HttpType.DEFAULT) {
                            list.clear()
                            list.addAll(it.data as Collection<LocalEntity>)
                        } else if (it.type == HttpType.UPLOAD) {
                            ToastUtils.showLong("上传成功")
                        }
                    }
                }
            }
        }
        vm.sendIntent(DocumentIntent.ScanFile(file!!))
    })

    Column(Modifier.padding(10.dp)) {
        Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
            Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "", modifier = Modifier.clickable {
                navHostController.popBackStack()
            })
            Text(text = "上传文件选择")
            Text(text = "上传",Modifier.clickable {
                vm.sendIntent(DocumentIntent.UploadDocument(checkName,checkPath))
            })
        }
        Spacer(modifier = Modifier.height(10.dp))
        LazyColumn(content = {
            items(list) {
                LocalItem(entity = it, it.fileName == checkName) {
                    checkName = it.fileName
                    checkPath = it.path
                }
            }
        }, verticalArrangement = Arrangement.spacedBy(10.dp))
    }
}

@Composable
fun LocalItem(entity: LocalEntity, checked: Boolean, onClick: () -> Unit) {
    Row {
        Box(
            modifier = Modifier
                .padding(5.dp)
                .clickable {
                    onClick()
                }, contentAlignment = Alignment.TopEnd
        ) {
            Image(painter = painterResource(id = R.drawable.document), contentDescription = "", Modifier.size(50.dp))
            val img = if (checked) R.drawable.ic_check else R.drawable.ic_uncheck
            Image(
                painter = painterResource(id = img),
                contentDescription = "",
                Modifier
                    .size(15.dp)
                    .offset(7.dp, (-7).dp)
            )
        }
        Spacer(modifier = Modifier.width(10.dp))
        Column(Modifier.height(50.dp), verticalArrangement = Arrangement.SpaceBetween) {
            Text(text = entity.fileName)
            Text(
                text = entity.path,
                color = Color.Gray,
                fontSize = 12.sp,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}